package com.yq.interview.study.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @ClassName ReadWriteLockDemo
 * @Description 读写锁
 * 读的时候，多个线程操作，写的时候单个线程操作
 * 原子性独一无二，
 * 写操作必须是原子加独占，整个过程是一个完整体，不允许被打断
 *
 * @Author yaoqiang
 * @Date 2020/11/19 13:42
 * @Version 1.0
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache =new MyCache();

       // Lock lock=new  ReentrantLock()

        for (int i=1;i<=5;i++){
            final int temp=i;
            new Thread(()->{
                myCache.put(temp+"",temp+"");
            },String.valueOf(i)).start();
        }
        for (int i=1;i<=5;i++){
            final int temp=i;
            new Thread(()->{
                myCache.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}

/**
 * 缓存
 */
class MyCache{
    private volatile Map<String,Object> map=new HashMap<>();
    private Lock lock=null;//new ReentrantLock()
    //写缓存3步， 读，写，清空

    /***
     * 写入方法
     * @param key
     * @param value
     */
    public  void put(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"正在写入"+key);
        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入完成");
    }

    public  void get(String key){
        System.out.println(Thread.currentThread().getName()+"正在读");
        try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
        Object result= map.get(key);
        System.out.println(Thread.currentThread().getName()+"读完"+result);
    }


}
